/*
 * Copyright Red Hat Inc. and/or its affiliates and other contributors
 * as indicated by the authors tag. All rights reserved.
 *
 * This copyrighted material is made available to anyone wishing to use,
 * modify, copy, or redistribute it subject to the terms and conditions
 * of the GNU General Public License version 2.
 * 
 * This particular file is subject to the "Classpath" exception as provided in the 
 * LICENSE file that accompanied this code.
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT A
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
 * PARTICULAR PURPOSE.  See the GNU General Public License for more details.
 * You should have received a copy of the GNU General Public License,
 * along with this distribution; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA  02110-1301, USA.
 */
package org.eclipse.ceylon.compiler.java.tools;

import org.eclipse.ceylon.common.StatusPrinter;
import org.eclipse.ceylon.compiler.java.loader.UnknownTypeCollector;
import org.eclipse.ceylon.compiler.java.loader.model.CompilerModuleManager;
import org.eclipse.ceylon.compiler.java.loader.model.LazyModuleSourceMapper;
import org.eclipse.ceylon.compiler.java.tools.LanguageCompiler.CompilerDelegate;
import org.eclipse.ceylon.compiler.typechecker.TypeChecker;
import org.eclipse.ceylon.compiler.typechecker.analyzer.ModuleSourceMapper;
import org.eclipse.ceylon.compiler.typechecker.analyzer.ModuleValidator;
import org.eclipse.ceylon.compiler.typechecker.context.PhasedUnit;
import org.eclipse.ceylon.compiler.typechecker.context.PhasedUnits;
import org.eclipse.ceylon.compiler.typechecker.io.VirtualFile;
import org.eclipse.ceylon.langtools.tools.javac.main.Option;
import org.eclipse.ceylon.langtools.tools.javac.tree.JCTree.JCCompilationUnit;
import org.eclipse.ceylon.langtools.tools.javac.util.Context;
import org.eclipse.ceylon.langtools.tools.javac.util.List;
import org.eclipse.ceylon.langtools.tools.javac.util.Options;
import org.eclipse.ceylon.model.loader.AbstractModelLoader;
import org.eclipse.ceylon.model.typechecker.model.Module;

public final class CeyloncCompilerDelegate implements
        CompilerDelegate {
    private final Context context;
    private CompilerModuleManager moduleManager;
    private LazyModuleSourceMapper moduleSourceMapper;

    public CeyloncCompilerDelegate(Context context) {
        this.context = context;
    }

    @Override
    public CompilerModuleManager getModuleManager() {
        if(moduleManager == null){
            org.eclipse.ceylon.compiler.typechecker.context.Context ceylonContext = LanguageCompiler.getCeylonContextInstance(context);
            moduleManager = new CompilerModuleManager(ceylonContext, context);
        }
        return moduleManager;
    }

    @Override
    public ModuleSourceMapper getModuleSourceMapper() {
        if(moduleSourceMapper == null){
            org.eclipse.ceylon.compiler.typechecker.context.Context ceylonContext = LanguageCompiler.getCeylonContextInstance(context);
            Options options = Options.instance(context);
            boolean verbose = options.isSet(Option.VERBOSE);
            CeylonLog log = (CeylonLog) CeylonLog.instance(context);
            moduleSourceMapper = new LazyModuleSourceMapper(ceylonContext, getModuleManager(), getStatusPrinter(),
                    verbose, log);
        }
        return moduleSourceMapper;
    }

    @Override
    public PhasedUnit getExternalSourcePhasedUnit(
            VirtualFile srcDir, VirtualFile file) {
        return null;
    }

    
    
    @Override
    public void typeCheck(java.util.List<PhasedUnit> listOfUnits) {
        StatusPrinter sp = getStatusPrinter();

        int size = listOfUnits.size();
        int i=1;
        for (PhasedUnit pu : listOfUnits) {
            if(sp != null)
                progress(sp, 1, i++, size, pu);
            pu.validateTree();
            pu.scanDeclarations();
        }
        i=1;
        for (PhasedUnit pu : listOfUnits) { 
            if(sp != null)
                progress(sp, 2, i++, size, pu);
            pu.scanTypeDeclarations(); 
        } 
        i=1;
        for (PhasedUnit pu: listOfUnits) { 
            if(sp != null)
                progress(sp, 3, i++, size, pu);
            pu.validateRefinement();
        }
        
        i=1;
        for (PhasedUnit pu : listOfUnits) { 
            if(sp != null)
                progress(sp, 4, i++, size, pu);
            pu.analyseTypes(); 
        }
        
        i=1;
        for (PhasedUnit pu : listOfUnits) { 
            if(sp != null)
                progress(sp, 5, i++, size, pu);
            pu.analyseFlow();
        }

        i=1;
        for (PhasedUnit pu : listOfUnits) { 
            if(sp != null)
                progress(sp, 6, i++, size, pu);
            pu.analyseUsage();
        }
        
        i=1;
        UnknownTypeCollector utc = new UnknownTypeCollector();
        for (PhasedUnit pu : listOfUnits) { 
            if(sp != null)
                progress(sp, 7, i++, size, pu);
            pu.getCompilationUnit().visit(utc);
        }
    }

    private StatusPrinter getStatusPrinter() {
        Options options = Options.instance(context);
        boolean isProgressPrinted = options.get(Option.CEYLONPROGRESS) != null && StatusPrinter.canPrint();
        if(isProgressPrinted){
            return LanguageCompiler.getStatusPrinterInstance(context);
        }else{
            return null;
        }
    }

    private void progress(StatusPrinter sp, int phase, int i, int size, PhasedUnit pu) {
        sp.clearLine();
        sp.log("Typechecking "+phase+"/7 ["+i+"/"+size+"] ");
        sp.log(pu.getPathRelativeToSrcDir());
    }

    @Override
    public void visitModules(PhasedUnits phasedUnits) {
        phasedUnits.visitModules();
    }

    @Override
    public void loadPackageDescriptors(AbstractModelLoader modelLoader) {
        modelLoader.loadPackageDescriptors();
    }

    @Override
    public void resolveModuleDependencies(PhasedUnits phasedUnits) {
        final StatusPrinter sp = getStatusPrinter();
        org.eclipse.ceylon.compiler.typechecker.context.Context ceylonContext = LanguageCompiler.getCeylonContextInstance(context);
        final ModuleValidator validator = new ModuleValidator(ceylonContext, phasedUnits);
        if(sp != null){
            validator.setListener(new StatusPrinterProgressListener(validator, sp));
            sp.clearLine();
            sp.log("Starting resolving");
        }
        validator.verifyModuleDependencyTree();
        if(sp != null){
            sp.clearLine();
            sp.log("Done resolving");
        }
    }

    @Override
    public void setupSourceFileObjects(List<JCCompilationUnit> trees, AbstractModelLoader modelLoader) {
        modelLoader.setupSourceFileObjects(trees);
    }

    @Override
    public void loadStandardModules(AbstractModelLoader modelLoader) {
        org.eclipse.ceylon.compiler.typechecker.context.Context ceylonContext = LanguageCompiler.getCeylonContextInstance(context);
        Module languageModule = ceylonContext.getModules().getLanguageModule();
        if (languageModule.getVersion() == null) {
            languageModule.setVersion(TypeChecker.LANGUAGE_MODULE_VERSION);
        }
        modelLoader.loadStandardModules();
    }
}